from flask import Blueprint,jsonify,request,json
from models import *
import os
user_bp = Blueprint('user_bp',__name__,url_prefix='/user')


# 获取相册
@user_bp.route("/xcindex")
def xcindex():
    xc_data = Xc.query.all()
    xc_list = []
    for i in xc_data:
        xc_list.append({
            'id':i.id,
            'name':i.name
        })
    return jsonify({"code":200,'data':xc_list})


# 获取图片
@user_bp.route("/tpindex")
def tpindex():
    tp_data = Tp.query.all()
    tp_list = []
    for i in tp_data:
        tp_list.append({
            'id':i.id,
            'url':i.url,
            'name':i.name,
            'x_id':i.x_id
        })
    return jsonify({"code":200,'data':tp_list})


# 获取相册下的数据
@user_bp.route("/leiindex/<int:id>")
def leiindex(id):
    lei_data = Tp.query.filter(Tp.x_id==id)
    lei_list = []
    for i in lei_data:
        lei_list.append({
            'id': i.id,
            'url': i.url,
            'name': i.name,
            'x_id': i.x_id
        })
    return jsonify({"code":200,'data':lei_list})


# 添加相册
@user_bp.route("/addxc",methods=['POST'])
def addxc():
    data = request.json
    id = data.get('id')
    name = data.get('name')
    assd = Xc(id=id,name=name)
    db.session.add(assd)
    db.session.commit()
    return jsonify({"code":200,'msg':"添加相册成功"})


# 添加图片
@user_bp.route("/addtp",methods=['POST'])
def addtp():
    data1 = request.json
    id = data1.get('id')
    url = data1.get('url')
    name = data1.get('name')
    x_id = data1.get('x_id')
    adds = Tp(id=id,url=url,name=name,x_id=x_id)
    db.session.add(adds)
    db.session.commit()
    return jsonify({"code":200,'msg':'添加图片成功'})


# 删除相册
@user_bp.route("/delxc/<int:id>",methods=['DELETE'])
def delxc(id):
    Xc.query.filter_by(id=id).delete()
    return jsonify({"code":200,'msg':'删除相册成功'})


# 删除图片
@user_bp.route("/deltp/<int:id>",methods=['DELETE'])
def deltp(id):
    Tp.query.filter_by(id=id).delete()
    return jsonify({"code":200,'msg':'删除图片成功'})


# 修改相册
@user_bp.route("/putxc",methods=['PUT'])
def putxc():
    data = json.loads(request.data)
    Xc.query.filter_by(id=id).update({
        'id':data['id'],
        'name':data['name']
    })
    db.session.commit()
    return jsonify({"code":200,'msg':'修改相册成功'})


# 图片上传
@user_bp.route("/upload",methods=['POST'])
def upload():
    file = request.files.get('file')
    path = os.path.join("static/"+file.filename)
    file.save(path)
    return jsonify({
        'code':200,
        'url':path
    })